package com.modai.service;

import com.modai.entity.Role;
import com.modai.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.jws.Oneway;
import java.beans.PropertyDescriptor;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ：modai
 * @date ：Created in 2021-6-5 18:22
 * @description：用户服务
 */
@Service
public class UserService {
    private final AtomicInteger userNum = new AtomicInteger(2);
    private final Map<Integer, User> map = new ConcurrentHashMap<Integer, User>(){{
        put(1,new User(1,
                        "xiaowang",
                        "1q2w3e34",
                        Arrays.asList(Role.admin,Role.developer)));
        put(2,new User(2,
                        "xiaoliu",
                        "1q2w3e54",
                        Arrays.asList(Role.admin,Role.test)));
    }};

    public User retrieveUser(Integer id){
        Assert.isTrue(map.containsKey(id),"user not exist");
        return map.get(id);
    }
    public User createUser(User user){
        int i = userNum.incrementAndGet();
        user.setId(i);
        map.put(i,user);
        return user;
    }
    public User deleteUser(Integer id){
        Assert.isTrue(map.containsKey(id),"user not exist");
        userNum.decrementAndGet();
        return map.remove(id);
    }
    public User updateUser(User user){
        Integer userId = user.getId();
        Assert.notNull(userId,"userId should not be null");
        Assert.isTrue(map.containsKey(userId),"user not exist");
        User userExist = map.get(userId);
        BeanUtils.copyProperties(user,userExist,getNullProperties(user));
        return userExist;
    }

    public Integer getUserNum(){
        return userNum.get();
    }

    private String[] getNullProperties(Object obj){
        BeanWrapperImpl src = new BeanWrapperImpl(obj);
        PropertyDescriptor[] descriptors = src.getPropertyDescriptors();
        HashSet<String> nullNames = new HashSet<>();
        for (PropertyDescriptor descriptor : descriptors) {
            Object propertyValue = src.getPropertyValue(descriptor.getName());
            if(propertyValue==null){
                nullNames.add(descriptor.getName());
            }
        }
        return nullNames.toArray(new String[0]);
    }
}
